<?php

namespace app\admin\controller\expert;

use app\common\controller\Backend;
use fast\Tree;
use think\Cache;

/**
 *  二星董事加权分红明细管理
 *
 * @icon   fa fa-list
 * @remark 
 */
class MarketingManagerWeightingScoreDetail extends Backend
{

    protected $searchFields = 'u.mobile';

    protected $level = "3";
    protected $type = "1";

    public function _initialize()
    {
        parent::_initialize();

        //月份列表
        $month = input("month", "");
        $monthList = $this->_monthList();
        $this->view->assign('monthList', build_select('row[monthList]', $monthList, $month, ['class' => 'form-control month-list']));
        $this->assignconfig('monthList', $monthList);
        $this->assignconfig('month', $month);


        //级别
        $this->assign("level", $this->level);
    }


    /**
     * 月份列表
     */
    private function _monthList()
    {
        $re[""] = "请选择月份";
        $StartMonth   = date('Y-m', strtotime('-6 Month')); //开始日期
        $EndMonth     = date('Y-m', strtotime('+1 Month', time())); //结束日期
        $ToStartMonth = strtotime($StartMonth); //转换一下
        $ToEndMonth   = strtotime($EndMonth); //一样转换一下
        $i            = false; //开始标示
        while ($ToStartMonth < $ToEndMonth) {
            $NewMonth = !$i ? date('Y-m', strtotime('+0 Month', $ToStartMonth)) : date('Y-m', strtotime('+1 Month', $ToStartMonth));
            $ToStartMonth = strtotime($NewMonth);
            $i = true;
            $key = date("Ym", strtotime($NewMonth . "-01 00:00:00"));
            $re[$key] = $NewMonth;
        }
        return $re;
        // exit(print_r($re));
    }

    /**
     * 列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '', 'trim'), true);

            //默认加入的查询条件
            $filter["uwsd.level"] = $this->level;
            $op["uwsd.level"] = "=";

            $filter["uwsd.type"] = $this->type;
            $op["uwsd.type"] = "=";

            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list_info = db("user_weighting_score_detail uwsd")
                ->join('user u', "uwsd.user_id=u.id", "LEFT")
                ->field("uwsd.*,u.nickname,u.avatar,u.mobile")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // exit(db()->getLastSql());

            $list = $list_info->items();
            $total = $list_info->total();

            foreach ($list as $k => $v) {
                // exit(print_r($v));

                $list[$k]["avatar"] = $v["avatar"] ? cdnurl($v["avatar"], true) : letter_avatar($v["nickname"]);
                unset($list[$k]["password"]);
                unset($list[$k]["salt"]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 开始分红
     */
    public function start_score()
    {
        $total_score = input("total_score");
        $month = input("month");
        $month_config = db("user_weighting_month_config")->where("level", $this->level)->where("month",  $month)->find();
        if ($month_config) {
            $this->error("本月已分红过一次");
        }

        $list = db("user_weighting_score_detail")->where("type", $this->type)->where("level", $this->level)->where("month", $month)->select();
        if ($list) {
            foreach ($list as $detail) {

                $score = intval($total_score * $detail["percent"] / 100);
                db("user_weighting_score_detail")->where("id", $detail["id"])->update([
                    "score" => $score,
                    "status" => 1,
                    "update_time" => time(),
                ]);

                //插入积分记录表
                $user_score = db("user")->where("id", $detail["user_id"])->value("score");

                db("user_score_log")->insert([
                    "titles" => "二星董事分红",
                    "user_id" => $detail["user_id"],
                    "score" => $score,
                    "before" => $user_score,
                    "after" => $user_score + $score,
                    "memo" => "二星董事分红",
                    "createtime" => time(),
                ]);

                db("user")->where("id", $detail["user_id"])->setInc("weighting_score", $score);
                db("user")->where("id", $detail["user_id"])->setInc("score", $score);
            }
            // exit(print_r($list));

            //添加到每月配置表
            db("user_weighting_month_config")->insert(["level" => $this->level, "month" =>  $month, "total" => $total_score, "addtime" => time()]);

            $this->success("分红已完成");
        } else {
            $this->error("没有分红的人员列表");
        }
    }


    /**
     * 生成记录
     */
    public function create_record()
    {
        $month = input("month");

        //删除旧数据
        db("user_weighting_score_detail")->where("type", $this->type)->where("level", $this->level)->where("month", $month)->delete();

        //生成新数据
        $list = db("user")->select();
        if ($list) {
            foreach ($list as $user) {
                $percent = 1 * 100 / count($list);
                $data = [
                    "user_id" => $user["id"],
                    "level" =>  $this->level,
                    "type" => $this->type,
                    "percent" => $percent,
                    "month" =>  $month,
                    "add_time" => time(),
                ];
                db("user_weighting_score_detail")->insert($data);
            }
            $this->success("生成记录成功");
        } else {
            $this->error("没有分红的人员");
        }
    }


    /**
     * 查询当月分红情况
     */
    public function query_month_score()
    {
        $month = input("month");
        $month_config = db("user_weighting_month_config")->where("level", $this->level)->where("month", $month)->find();
        if ($month_config) {
            $this->success("本月已分红过", "", $month_config);
        } else {
            $this->error("本月未分红过", "", ["month" => $month]);
        }
    }
}
